﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace Attendance
{
    public partial class frmPort1 : Form
    {
        string[] ports = SerialPort.GetPortNames();
        public SerialPort serialPort1;
        public string s100 = "0";//物理卡号

        public frmPort1()
        {
            InitializeComponent();
            //MessageBox.Show(ports.GetValue(0).ToString());
            bgwCheckPorts.RunWorkerAsync();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bgwCheckPorts_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                
                if (ports.Length != 0)
                { break; }
            }
        }

        private void bgwCheckPorts_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled == true)
            {
                MessageBox.Show("Cancelled");
            }
            else
            {
                serialPort1 = new SerialPort(ports[0], 9600);
                serialPort1.Open();
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(ReadPort);
            }
        }

        void ReadPort(Object sender, SerialDataReceivedEventArgs e)
        {
            GetWulikahao();
        }

        private void GetWulikahao()
        {
            //获取物理卡号过程
            s100 = "0";
            Thread.Sleep(100);
            MessageBox.Show(s100);
            byte[] readBuffer = new byte[4];
            serialPort1.Read(readBuffer, 0, 4);
            s100 = ByteArrayToHexString(readBuffer);
            s100 = s100.Replace(" ", "");

            //十六进制的物理卡号转成十进制
            s100 = Convert.ToInt64(s100, 16).ToString();
            MessageBox.Show(s100);
        }

        public static string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            string a = sb.ToString();
            return sb.ToString().ToUpper();
        }

    }
}
